const parser = require("@babel/parser");
const generator = require("@babel/generator").default;
const traverse = require("@babel/traverse").default;
const t = require("@babel/types");
const code = `import { _decorator, Component, Contact2DType, EventTouch, Label, log, Node, PhysicsSystem2D, Size, Sprite, tween, UIOpacity, UITransform, v2, v3, Vec2, Vec3 } from 'cc';
import BaseLevelUI from '../../controller/BaseLevelUI';

const { ccclass, property } = _decorator;

@ccclass('MyComponent')
export class MyComponent extends Component {
    start() {
        const position = v3(0, 0, 0);
        this.node.setPosition(position);
    }
}`;

const ast = parser.parse(code, {
  sourceType: "module", // 使用 ES 模块
  plugins: [
    // 如果代码中使用了 TypeScript 或 JSX
    "typescript",
    "decorators-legacy"
  ]
});


traverse(ast, {
    ImportDeclaration(path) {
        if (path.node.source.value === 'cc') {
          // Replace import from 'cc' with global cc
          path.remove();
        }
      },
      Identifier(path) {
        if (path.node.name === '_decorator') {
          path.node.name = 'cc';
        }
        if (path.node.name === 'v3') {
          path.node.name = 'cc.v2';
        }
        if (path.node.name === 'Vec3') {
          path.node.name = 'cc.Vec2';
        }
        if (path.node.name === 'Component') {
          path.node.name = 'cc.Component';
        }
        if (path.node.name === 'Node') {
          path.node.name = 'cc.Node';
        }
      },
      ClassDeclaration(path) {
        const decorators = path.node.decorators;
        if (decorators) {
          decorators.forEach(decorator => {
            if (t.isCallExpression(decorator.expression) && decorator.expression.callee.name === 'ccclass') {
              decorator.expression.callee.name = 'cc.Class';
            }
          });
        }
      },
      CallExpression(path) {
        if (path.node.callee.name === 'v3') {
          path.node.callee.name = 'cc.v2';
        }
      }
});
const output = generator(ast);
console.log(output);